// pages/people/add/add.js
import { getPeopleDetail, getPeoplePhotoUrl } from '../../../utils/people'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'household', // 默认显示基本信息
    id: '',
    formData: {
      // 户主信息
      householder: {
        name: '', // 姓名
        relation: '户主', // 关系
        photoUrl: '', // 照片URL
        idNumber: '', // 身份证号
        address: '', // 户籍地址
        currentAddress: '',
        gender: '男', // 性别
        birthday: '', // 出生年月
        ethnicity: '汉族', // 民族
        region: '城市', // 地域
        political: '群众', // 政治面貌
        maritalStatus: '未婚', // 婚姻状况
        education: '初中', // 文化程度
        phone: '', // 电话
        administrativeDivisions: '', // 行政区划
        remark: '', // 备注

        // 工作情况
        workUnit: '', // 工作单位/学校
        workStatus: '单位职工', // 工作情况

        // 健康状况
        bloodType: 'A型', // 血型
        limbsActivity: '自如', // 四肢活动
        medicalHistory: '', // 既往病史
        recordDisease: '', // 建档时疾病

        longTermMedication: '否', // 长期用药
        majorDiseases: '', // 重大疾病
        healthStatus: '良好', // 健康状况
        disabilityType: '无', // 伤残类别
        disabilityLevel: '', // 伤残等级
        abilityLevel: '', // 能力评定结果
        healthremarks: '', // 健康备注

        // 社会保障
        medicalInfo: '', // 医疗
        pensionInfo: '', // 养老
        housingInfo: '', // 住房
        lowIncomeInfo: '', // 低保
        insuranceInfo: '', // 保险
        fiveGuaranteesInfo: '', // 五保
        otherInsuranceInfo: '', // 其他保障
        employmentSupportInfo: '', // 就业扶持
      },

      // 配偶信息
      spouse: {
        name: '', // 姓名
        relation: '配偶', // 关系
        photoUrl: '', // 照片URL
        idNumber: '', // 身份证号
        address: '', // 户籍地址
        currentAddress: '', // 现住址
        gender: '女', // 性别
        birthday: '', // 出生年月
        ethnicity: '汉族', // 民族
        region: '城市', // 地域
        political: '群众', // 政治面貌
        maritalStatus: '已婚', // 婚姻状况
        education: '初中', // 文化程度
        phone: '', // 电话

        // 行政区划
        province: '', // 省
        provinceCode: '', // 省代码
        city: '', // 市
        cityCode: '', // 市代码
        district: '', // 区/县
        districtCode: '', // 区/县代码
        administrativeDivisions: '', // 行政区划
        remark: '', // 备注
        // 工作情况
        workUnit: '', // 工作单位/学校
        workStatus: '单位职工', // 工作情况

        // 健康状况
        bloodType: 'A型', // 血型
        limbsActivity: '自如', // 四肢活动
        medicalHistory: '', // 既往病史
        recordDisease: '', // 建档时疾病
        longTermMedication: '否', // 长期用药
        majorDiseases: '', // 重大疾病
        healthStatus: '良好', // 健康状况
        disabilityType: '无', // 伤残类别
        disabilityLevel: '', // 伤残等级
        abilityLevel: '', // 能力评定结果
        healthremarks: '', // 健康备注

        // 社会保障
        medicalInfo: '', // 医疗
        pensionInfo: '', // 养老
        housingInfo: '', // 住房
        lowIncomeInfo: '', // 低保
        insuranceInfo: '', // 保险
        fiveGuaranteesInfo: '', // 五保
        otherInsuranceInfo: '', // 其他保障
        employmentSupportInfo: '', // 就业扶持
      },

      // 家庭情况
      familyLevel: '', // 家庭等级
      income: '', // 年收入
      expense: '', // 年支出

      // 行政区划
      province: '', // 省
      provinceCode: '', // 省代码
      city: '', // 市
      cityCode: '', // 市代码
      district: '', // 区/县
      districtCode: '', // 区/县代码
      street: '', // 街道
      streetCode: '', // 街道代码

      // 成员信息（数组形式，支持多个子女）
      memberList: [{
        name: '', // 姓名
        relation: '', // 关系
        isAdopted: '否', // 是否收养
        gender: '男', // 性别
        birthday: '', // 出生日期
        healthStatus: '', // 健康状况
        selfCareAbility: '', // 生活自理能力
        isLivingAlone: '否', // 是否独居
        disabilityType: '', // 伤残类别 
        disabilityLevel: '', // 伤残等级
        medicalDependencyType: '', // 医疗依赖类型
        hasChronicDisease: '否', // 是否有慢性病
        chronicDiseaseName: '', // 慢性病名称
        regularMedication: '', // 常用药物
        abilityLevel: '', // 等级划分
        remarks: '' // 备注
      }],
    },

  },
  /**
   * 切换左侧边栏
   */
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    getPeopleDetail(this.data.id).then(res => {
      const data = res.data
      // console.log(data);

      //拿出基本信息
      this.setData({
        'formData.id': data.uid,
        'formData.familyLevel': data.grading,
        'formData.income': data.annualIncome,
        'formData.expense': data.annualExpenditure,
        'formData.province': data.provinceName,
        'formData.city': data.municipalityName,
        'formData.district': data.districtName,
        'formData.street': data.townshipStreetsName,
      })
      // //拿出本人信息
      const self = data.listHouseHoldSpouse.find(item => item.relation === '户主')
      //获取户主照片
      if (self.photoUrl && self.photoUrl !== '无') {
        getPeoplePhotoUrl({
          'photokey': self.photoUrl
        }).then(res => {
          // console.log(res);
          this.setData({
            'formData.householder.photoUrl': res.data
          })
        })
      }
      // //拿出配偶信息
      const spouse = data.listHouseHoldSpouse.find(item => item.relation === '配偶')
      //获取配偶照片
      if (spouse && spouse.photoUrl && spouse.photoUrl !== '无') {
        getPeoplePhotoUrl({
          'photokey': spouse.photoUrl
        }).then(res => {
          // console.log(res);
          this.setData({
            'formData.spouse.photoUrl': res.data
          })
        })
      }

      //设置户主信息
      this.setData({
        'formData.householder.name': self.name,
        'formData.householder.relation': self.relation,
        // 'formData.householder.photoUrl': self.photoUrl,
        'formData.householder.idNumber': self.identificationNumber,
        'formData.householder.address': self.householdRegistLocation,
        'formData.householder.currentAddress': self.currentPlace,
        'formData.householder.gender': self.gender,
        //只保留年月日
        'formData.householder.birthday': self.birthDate.split('T')[0],
        'formData.householder.ethnicity': self.ethnicity,
        'formData.householder.region': self.region,
        'formData.householder.political': self.politicalAffiliation,
        'formData.householder.maritalStatus': self.maritalStatus,
        'formData.householder.education': self.educationLevel,
        'formData.householder.phone': self.phoneNumber,
        'formData.householder.administrativeDivisions': self.administrativeDivision,
        'formData.householder.remark': self.remark,
        'formData.householder.workUnit': self.employerSchool,
        'formData.householder.workStatus': self.employmentStatus,
        'formData.householder.abilityLevel': self.grading,
        //健康状况
        'formData.householder.bloodType': self.healthInformation.bloodType,
        'formData.householder.limbsActivity': self.healthInformation.limbMobility,
        'formData.householder.medicalHistory': self.healthInformation.medicalHistory,
        'formData.householder.recordDisease': self.healthInformation.recordDisease,
        'formData.householder.longTermMedication': self.healthInformation.isLongTermMedication,
        'formData.householder.majorDiseases': self.healthInformation.majorDiseases,
        'formData.householder.healthStatus': self.healthInformation.healthStatus,
        'formData.householder.disabilityType': self.healthInformation.disabilityType,
        'formData.householder.disabilityLevel': self.healthInformation.disabilityLevel,
        'formData.householder.healthremarks': self.healthInformation.remark,
        //社会保障
        'formData.householder.medicalInfo': self.socialSecurityInformation.medicalInsurance,
        'formData.householder.pensionInfo': self.socialSecurityInformation.pensionInsurance,
        'formData.householder.housingInfo': self.socialSecurityInformation.housingFund,
        'formData.householder.lowIncomeInfo': self.socialSecurityInformation.lowIncomeSupport,
        'formData.householder.insuranceInfo': self.socialSecurityInformation.insurance,
        'formData.householder.fiveGuaranteesInfo': self.socialSecurityInformation.fiveGuaranteesSupport,
        'formData.householder.otherInsuranceInfo': self.socialSecurityInformation.otherBenefits,
        'formData.householder.employmentSupportInfo': self.socialSecurityInformation.employmentSupport,
      })
      //设置配偶信息
      if (spouse) {
        //设置户主信息
        this.setData({
          'formData.spouse.name': spouse.name,
          'formData.spouse.relation': spouse.relation,
          // 'formData.spouse.photoUrl': spouse.photoUrl,
          'formData.spouse.idNumber': spouse.identificationNumber,
          'formData.spouse.address': spouse.householdRegistLocation,
          'formData.spouse.gender': spouse.gender,
          //只保留年月日
          'formData.spouse.birthday': spouse.birthDate.split('T')[0],
          'formData.spouse.ethnicity': spouse.ethnicity,
          'formData.spouse.region': spouse.region,
          'formData.spouse.currentAddress': spouse.currentPlace,
          'formData.spouse.political': spouse.politicalAffiliation,
          'formData.spouse.maritalStatus': spouse.maritalStatus,
          'formData.spouse.education': spouse.educationLevel,
          'formData.spouse.phone': spouse.phoneNumber,
          'formData.spouse.administrativeDivisions': spouse.administrativeDivision,
          'formData.spouse.remark': spouse.remark,
          'formData.spouse.workUnit': spouse.employerSchool,
          'formData.spouse.workStatus': spouse.employmentStatus,
          'formData.spouse.abilityLevel': spouse.grading,
          //健康状况
          'formData.spouse.bloodType': spouse.healthInformation.bloodType,
          'formData.spouse.limbsActivity': spouse.healthInformation.limbMobility,
          'formData.spouse.medicalHistory': spouse.healthInformation.medicalHistory,
          'formData.spouse.recordDisease': spouse.healthInformation.recordDisease,
          'formData.spouse.longTermMedication': spouse.healthInformation.isLongTermMedication,
          'formData.spouse.majorDiseases': spouse.healthInformation.majorDiseases,
          'formData.spouse.healthStatus': spouse.healthInformation.healthStatus,
          'formData.spouse.disabilityType': spouse.healthInformation.disabilityType,
          'formData.spouse.disabilityLevel': spouse.healthInformation.disabilityLevel,
          'formData.spouse.healthremarks': spouse.healthInformation.remark,
          //社会保障
          'formData.spouse.medicalInfo': spouse.socialSecurityInformation.medicalInsurance,
          'formData.spouse.pensionInfo': spouse.socialSecurityInformation.pensionInsurance,
          'formData.spouse.housingInfo': spouse.socialSecurityInformation.housingFund,
          'formData.spouse.lowIncomeInfo': spouse.socialSecurityInformation.lowIncomeSupport,
          'formData.spouse.insuranceInfo': spouse.socialSecurityInformation.insurance,
          'formData.spouse.fiveGuaranteesInfo': spouse.socialSecurityInformation.fiveGuaranteesSupport,
          'formData.spouse.otherInsuranceInfo': spouse.socialSecurityInformation.otherBenefits,
          'formData.spouse.employmentSupportInfo': spouse.socialSecurityInformation.employmentSupport,
        })
      }
      //拿出子女信息
      const memberList = data.listChildGrand
      if (memberList.length > 0) {
        for (let i = 0; i < memberList.length; i++) {
          const member = memberList[i]
          let dataObj = {};
          dataObj[`formData.memberList[${i}].name`] = member.name;
          dataObj[`formData.memberList[${i}].relation`] = member.relation;
          dataObj[`formData.memberList[${i}].isAdopted`] = member.ifAdopt;
          dataObj[`formData.memberList[${i}].gender`] = member.gender;
          //只保留年月日
          dataObj[`formData.memberList[${i}].birthday`] = member.birthDate.split('T')[0];
          dataObj[`formData.memberList[${i}].healthStatus`] = member.healthStatus;
          dataObj[`formData.memberList[${i}].selfCareAbility`] = member.takecareLifeAbility;
          dataObj[`formData.memberList[${i}].isLivingAlone`] = member.ifLivingAlone;
          dataObj[`formData.memberList[${i}].disabilityType`] = member.disabilityType;
          dataObj[`formData.memberList[${i}].disabilityLevel`] = member.disabilityLevel;
          dataObj[`formData.memberList[${i}].medicalDependencyType`] = member.medicalDependence;
          dataObj[`formData.memberList[${i}].hasChronicDisease`] = member.ifChronicDisease;
          dataObj[`formData.memberList[${i}].chronicDiseaseName`] = member.chronicDiseaseName;
          dataObj[`formData.memberList[${i}].regularMedication`] = member.commonlyMedications;
          dataObj[`formData.memberList[${i}].abilityLevel`] = member.grading;
          dataObj[`formData.memberList[${i}].remarks`] = member.remark;
          this.setData(dataObj);
        }
      }
      // console.log(this.data.formData)
    })
  },
  copyText: function (e) {
    const key = e.currentTarget.dataset.key;
    wx.setClipboardData({
      data: key,
      success: function () {
        wx.showToast({
          title: '已复制',
          icon: 'success',
          duration: 1000
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const id = options.id
    this.setData({
      id: id
    })
    getPeopleDetail(id).then(res => {
      const data = res.data
      console.log("家庭基本信息：",data);

      //拿出基本信息
      this.setData({
        'formData.id': data.uid,
        'formData.familyLevel': data.grading,
        'formData.income': data.annualIncome,
        'formData.expense': data.annualExpenditure,
        'formData.province': data.provinceName,
        'formData.city': data.municipalityName,
        'formData.district': data.districtName,
        'formData.street': data.townshipStreetsName,
      })
      // //拿出本人信息
      const self = data.listHouseHoldSpouse.find(item => item.relation === '户主')
      if (self.photoUrl && self.photoUrl !== '无') {
        //获取户主照片
        getPeoplePhotoUrl({
          'photokey': self.photoUrl
        }).then(res => {
          // console.log(res);
          this.setData({
            'formData.householder.photoUrl': res.data
          })
        })
      }
      // //拿出配偶信息
      const spouse = data.listHouseHoldSpouse.find(item => item.relation === '配偶')
      if (spouse && spouse.photoUrl && spouse.photoUrl !== '无') {
      //获取配偶照片
      if (spouse) {
        getPeoplePhotoUrl({
          'photokey': spouse.photoUrl
        }).then(res => {
          // console.log(res);
          this.setData({
            'formData.spouse.photoUrl': res.data
          })
        })
      }
    }

      //设置户主信息
      this.setData({
        'formData.householder.name': self.name,
        'formData.householder.relation': self.relation,
        // 'formData.householder.photoUrl': self.photoUrl,
        'formData.householder.idNumber': self.identificationNumber,
        'formData.householder.address': self.householdRegistLocation,
        'formData.householder.gender': self.gender,
        //只保留年月日
        'formData.householder.birthday': self.birthDate.split('T')[0],
        'formData.householder.ethnicity': self.ethnicity,
        'formData.householder.region': self.region,
        'formData.householder.political': self.politicalAffiliation,
        'formData.householder.maritalStatus': self.maritalStatus,
        'formData.householder.education': self.educationLevel,
        'formData.householder.phone': self.phoneNumber,
        'formData.householder.administrativeDivisions': self.administrativeDivision,
        'formData.householder.remark': self.remark,
        'formData.householder.workUnit': self.employerSchool,
        'formData.householder.workStatus': self.employmentStatus,
        'formData.householder.abilityLevel': self.grading,
        //健康状况
        'formData.householder.bloodType': self.healthInformation.bloodType,
        'formData.householder.limbsActivity': self.healthInformation.limbMobility,
        'formData.householder.medicalHistory': self.healthInformation.medicalHistory,
        'formData.householder.recordDisease': self.healthInformation.recordDisease,
        'formData.householder.longTermMedication': self.healthInformation.isLongTermMedication,
        'formData.householder.majorDiseases': self.healthInformation.majorDiseases,
        'formData.householder.healthStatus': self.healthInformation.healthStatus,
        'formData.householder.disabilityType': self.healthInformation.disabilityType,
        'formData.householder.disabilityLevel': self.healthInformation.disabilityLevel,
        'formData.householder.healthremarks': self.healthInformation.remark,
        //社会保障
        'formData.householder.medicalInfo': self.socialSecurityInformation.medicalInsurance,
        'formData.householder.pensionInfo': self.socialSecurityInformation.pensionInsurance,
        'formData.householder.housingInfo': self.socialSecurityInformation.housingFund,
        'formData.householder.lowIncomeInfo': self.socialSecurityInformation.lowIncomeSupport,
        'formData.householder.insuranceInfo': self.socialSecurityInformation.insurance,
        'formData.householder.fiveGuaranteesInfo': self.socialSecurityInformation.fiveGuaranteesSupport,
        'formData.householder.otherInsuranceInfo': self.socialSecurityInformation.otherBenefits,
        'formData.householder.employmentSupportInfo': self.socialSecurityInformation.employmentSupport,
      })
      //设置配偶信息
      if (spouse) {
        //设置户主信息
        this.setData({
          'formData.spouse.name': spouse.name,
          'formData.spouse.relation': spouse.relation,
          // 'formData.spouse.photoUrl': spouse.photoUrl,
          'formData.spouse.idNumber': spouse.identificationNumber,
          'formData.spouse.address': spouse.householdRegistLocation,
          'formData.spouse.gender': spouse.gender,
          //只保留年月日
          'formData.spouse.birthday': spouse.birthDate.split('T')[0],
          'formData.spouse.ethnicity': spouse.ethnicity,
          'formData.spouse.region': spouse.region,
          'formData.spouse.political': spouse.politicalAffiliation,
          'formData.spouse.maritalStatus': spouse.maritalStatus,
          'formData.spouse.education': spouse.educationLevel,
          'formData.spouse.phone': spouse.phoneNumber,
          'formData.spouse.administrativeDivisions': spouse.administrativeDivision,
          'formData.spouse.remark': spouse.remark,
          'formData.spouse.workUnit': spouse.employerSchool,
          'formData.spouse.workStatus': spouse.employmentStatus,
          'formData.spouse.abilityLevel': spouse.grading,
          //健康状况
          'formData.spouse.bloodType': spouse.healthInformation.bloodType,
          'formData.spouse.limbsActivity': spouse.healthInformation.limbMobility,
          'formData.spouse.medicalHistory': spouse.healthInformation.medicalHistory,
          'formData.spouse.recordDisease': spouse.healthInformation.recordDisease,
          'formData.spouse.longTermMedication': spouse.healthInformation.isLongTermMedication,
          'formData.spouse.majorDiseases': spouse.healthInformation.majorDiseases,
          'formData.spouse.healthStatus': spouse.healthInformation.healthStatus,
          'formData.spouse.disabilityType': spouse.healthInformation.disabilityType,
          'formData.spouse.disabilityLevel': spouse.healthInformation.disabilityLevel,
          'formData.spouse.healthremarks': spouse.healthInformation.remark,
          //社会保障
          'formData.spouse.medicalInfo': spouse.socialSecurityInformation.medicalInsurance,
          'formData.spouse.pensionInfo': spouse.socialSecurityInformation.pensionInsurance,
          'formData.spouse.housingInfo': spouse.socialSecurityInformation.housingFund,
          'formData.spouse.lowIncomeInfo': spouse.socialSecurityInformation.lowIncomeSupport,
          'formData.spouse.insuranceInfo': spouse.socialSecurityInformation.insurance,
          'formData.spouse.fiveGuaranteesInfo': spouse.socialSecurityInformation.fiveGuaranteesSupport,
          'formData.spouse.otherInsuranceInfo': spouse.socialSecurityInformation.otherBenefits,
          'formData.spouse.employmentSupportInfo': spouse.socialSecurityInformation.employmentSupport,
        })
      }
      //拿出子女信息
      const memberList = data.listChildGrand
      if (memberList.length > 0) {
        for (let i = 0; i < memberList.length; i++) {
          const member = memberList[i]
          let dataObj = {};
          dataObj[`formData.memberList[${i}].name`] = member.name;
          dataObj[`formData.memberList[${i}].relation`] = member.relation;
          dataObj[`formData.memberList[${i}].isAdopted`] = member.ifAdopt;
          dataObj[`formData.memberList[${i}].gender`] = member.gender;
          //只保留年月日
          dataObj[`formData.memberList[${i}].birthday`] = member.birthDate.split('T')[0];
          dataObj[`formData.memberList[${i}].healthStatus`] = member.healthStatus;
          dataObj[`formData.memberList[${i}].selfCareAbility`] = member.takecareLifeAbility;
          dataObj[`formData.memberList[${i}].isLivingAlone`] = member.ifLivingAlone;
          dataObj[`formData.memberList[${i}].disabilityType`] = member.disabilityType;
          dataObj[`formData.memberList[${i}].disabilityLevel`] = member.disabilityLevel;
          dataObj[`formData.memberList[${i}].medicalDependencyType`] = member.medicalDependence;
          dataObj[`formData.memberList[${i}].hasChronicDisease`] = member.ifChronicDisease;
          dataObj[`formData.memberList[${i}].chronicDiseaseName`] = member.chronicDiseaseName;
          dataObj[`formData.memberList[${i}].regularMedication`] = member.commonlyMedications;
          dataObj[`formData.memberList[${i}].abilityLevel`] = member.grading;
          dataObj[`formData.memberList[${i}].remarks`] = member.remark;
          this.setData(dataObj);
        }
      }
      // console.log(this.data.formData)
    })
  },

  // 预览图片
  previewImage: function (e) {
    // 根据点击的元素确定要预览的图片
    let photoUrl = '';
    if (this.data.activeTab === 'household' && this.data.formData.householder.photoUrl && this.data.formData.householder.photoUrl !== '无') {
      photoUrl = this.data.formData.householder.photoUrl;
    } else if (this.data.activeTab === 'spouse' && this.data.formData.spouse.photoUrl && this.data.formData.spouse.photoUrl !== '无') {
      photoUrl = this.data.formData.spouse.photoUrl;
    }

    if (photoUrl) {
      wx.previewImage({
        urls: [photoUrl],
        current: photoUrl
      });
    }
  },

  // 处理编辑按钮点击
  handleEdit: function () {
    const id = this.data.formData.id;
    wx.navigateTo({
      url: `/pages/people/add/add?id=${id}`
    });
  },

  // 处理导出按钮点击
  handleExport: function () {
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none',
      duration: 2000
    });
  },

  // 处理去探访按钮点击
  handleVisit: function () {
    const id = this.data.formData.id;
    wx.navigateTo({
      url: `/pages/visit/edit/edit?id=${id}`
    });
  }
})